package com.coolmusic;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.List;

public class MyFragment extends Fragment {

    private ListView musicListView;
    private Button logoutButton;
    private TextView userNameTextView, userEmailTextView;
    private SharedPreferences sharedPreferences;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_my, container, false);

        // 初始化组件
        musicListView = view.findViewById(R.id.my_music_list);
        logoutButton = view.findViewById(R.id.btn_logout);
        userNameTextView = view.findViewById(R.id.user_name);
        userEmailTextView = view.findViewById(R.id.user_email);

        // 加载用户信息
        sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", 0);
        String username = sharedPreferences.getString("current_username", "未登录");
        userNameTextView.setText(username);
        userEmailTextView.setText(username + "@example.com");

        // 设置音乐列表
        setupMusicList();

        // 退出登录
        logoutButton.setOnClickListener(v -> {
            sharedPreferences.edit().remove("current_username").apply();
            startActivity(new Intent(requireContext(), MainActivity.class));
            requireActivity().finish();
        });

        return view;
    }


    private void setupMusicList() {
        // 歌曲列表（顺序需与MusicFragment的musicList一致）
        List<String> musicTitles = new ArrayList<>();
        musicTitles.add("我们的明天 - 鹿晗");
        musicTitles.add("致爱 - 鹿晗");
        musicTitles.add("勋章 - 鹿晗");
        musicTitles.add("晴天 - 周杰伦");
        musicTitles.add("天天 - 陶喆");
        musicTitles.add("后来 - 刘若英");
        musicTitles.add("知足 - 五月天");
        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                requireContext(),
                android.R.layout.simple_list_item_1,
                musicTitles
        );
        musicListView.setAdapter(adapter);

        // 点击事件：传递歌曲索引
        musicListView.setOnItemClickListener((parent, view, position, id) -> {
            if (getActivity() instanceof MusicActivity) {
                MusicActivity activity = (MusicActivity) getActivity();
                activity.showHomeFragmentWithSongIndex(position); // 传递点击位置作为索引
            }
        });
    }
}